package com.nova.bluetooth.xunFeiSDK.utils;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class FileNameTextWatcher implements TextWatcher {
    private EditText editText;

    public FileNameTextWatcher(EditText editText) {
        this.editText = editText;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        // 在文本变化之前执行
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        // 文本变化时执行
        String input = charSequence.toString();
        String filteredInput = filterFileName(input);
        if (!input.equals(filteredInput)) {
            editText.setText(filteredInput);
            editText.setSelection(filteredInput.length()); // 将光标移到末尾
        }

        if (onTextChanged != null){
            onTextChanged.onTextChanged(charSequence,i,i1,i2);
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {
        // 在文本变化之后执行
        if (onTextChanged != null){
            onTextChanged.afterTextChanged(editable);
        }
    }

    private String filterFileName(String input) {
        // 实现文件命名规则的过滤逻辑
        // 这里你可以根据规则过滤掉不符合条件的字符
        // 例如，移除特殊字符、确保不以短划线或下划线开头或结尾等
        // 返回符合规则的字符串

        // 只能包含字母、数字、下划线和短划线
        // 只允许字母、数字、下划线、短划线和中文字符
//        String filteredInput = input.replaceAll("[^a-zA-Z0-9_\\-\\p{Punct}\\p{InCJKUnifiedIdeographs}]", "");

        // 允许字母、数字、下划线、短划线、空格和中文字符
        String filteredInput = input.replaceAll("[^a-zA-Z0-9_\\-\\s\\p{Punct}\\p{InCJKUnifiedIdeographs}]", "");


        // 不能以短划线或下划线开头
        if (filteredInput.startsWith("-") || filteredInput.startsWith("_")) {
            filteredInput = filteredInput.substring(1);
        }

        // 不能以短划线或下划线结尾
        if (filteredInput.endsWith("-") || filteredInput.endsWith("_")) {
            filteredInput = filteredInput.substring(0, filteredInput.length() - 1);
        }
        return filteredInput;
    }

    private OnTextChanged onTextChanged;

    public void setOnTextChanged(OnTextChanged onTextChanged) {
        this.onTextChanged = onTextChanged;
    }

    public interface OnTextChanged{
        void onTextChanged(CharSequence charSequence, int i, int i1, int i2);
         void afterTextChanged(Editable s) ;
    }
}
